<?php
declare(strict_types=1);

namespace SixShop\Auth\Hook;

use Composer\Factory;
use SixShop\Auth\Config;
use SixShop\Core\Attribute\Hook;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use think\Env;
use think\facade\Log;

class AppStatusHook
{

    private const string BASE_URL = 'https://apix.jd29.com';

    private const string PACKAGIST_DOMAIN = 'packagist.jd29.com';

    private HttpClientInterface $httpClient;
    public function __construct(
        private readonly Config $config,
    )
    {
        try {
            $authConfigSource = Factory::createConfig()->getAuthConfigSource();
            $authFile = $authConfigSource->getName();
            if (!file_exists($authFile)) {
                $authFile = root_path('runtime').'auth.json';
            }
        } catch (\RuntimeException) {
            $authFile = root_path('runtime').'auth.json';
        }
        $authJsonArr = json_decode(file_get_contents($authFile), true);
        $bearerToken = $authJsonArr['bearer'][self::PACKAGIST_DOMAIN];
        $defaultOptions = [
            'base_uri' => self::BASE_URL,
            'auth_bearer' => $bearerToken,
        ];
        $defaultOptions['verify_peer'] = $this->config->verify_peer;
        $defaultOptions['verify_host'] = $this->config->verify_host;
        $this->httpClient = HttpClient::create($defaultOptions);
    }

    #[Hook('post_app_status')]
    public function postAppStatus(array $data): void
    {
        try {
            $this->httpClient->request('POST', '/php/app_status', [
                'json' => $data
            ]);
        } catch (ClientException | TransportExceptionInterface $e) {
            Log::error($e->getMessage());
            Log::error(json_encode($e->getResponse()->toArray(false)));
        }
    }
}